const express = require('express')
const router = express.Router()
const humps = require('humps')
const db = require('../../database/db')

module.exports = (() => {
    // 订单管理
    router.get('/warrants', async (req, res, next) => {
        try {
            let sql = ''
            req.query.pick === '未提车' ? sql += 'AND r.`is_pick_car` = 0 ' :
                req.query.pick === '已提车' ? sql += 'AND r.`is_pick_car` = 1 ' : ''

            req.query.pass === '未审过' ? sql += 'AND r.`pass_time` = "" ' :
                req.query.pass === '已审过' ? sql += 'AND r.`pass_time` != "" ' : ''

            req.query.warrant ? sql += 'AND r.`warrant_man_id` = ' + req.query.warrant + ' ' : ''
            if (+req.query.depositToAchievement) {
                sql += 'AND r.`deposit_to_achievement` = 1 '
            } else {
                sql += 'AND r.`deposit_to_achievement` = 0 '
            }

            const doc = humps.camelizeKeys(await db.getWarrants({ limit: req.query.limit, offset: req.query.offset, search: req.query.search, sql }))
            const { total } = await db.getWarrantsTotal({ search: req.query.search, sql })
            const temp = []
            const promises = []
            doc.forEach(item => {
                const promise = new Promise(async resolve => {
                    const notpass = item.notpass && await db.getNotpassById(item.notpass) // 判断如果存在
                    const trial = item.trial && await db.getTrialById(item.trial)
                    const warrantMan = item.warrantManId && await db.getWarrantManById(item.warrantManId)
                    const cancellation = item.cancellation && await db.getCancellationById(item.cancellation)
                    item.notpass = notpass ? notpass.name : ''
                    item.trial = trial ? trial.name : ''
                    item.warrantMan = warrantMan ? warrantMan.name : ''
                    item.cancellation = cancellation ? cancellation.name : ''
                    temp.push(item)
                    resolve()
                })
                promises.push(promise)
            })

            Promise.all(promises).then((data) => {
                res.send({
                    doc,
                    total
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editWarrant/:id', async (req, res, next) => {
        try {
            let existWarrant = await db.getWarrantById(req.params.id)
            if (!existWarrant) {
                return res.json({
                    status: 0,
                    msg: '该订单不存在！'
                })
            }

            let trial = ''
            let notpass = ''
            let cancellation = ''
            let warrantMan = ''

            if (req.body.trial) {
                trial = await db.getTrialByName(req.body.trial)
            }

            if (req.body.notpass) {
                notpass = await db.getNotpassByName(req.body.notpass)
            }
            if (req.body.cancellation) {
                cancellation = await db.getCancellationByName(req.body.cancellation)
            }

            if (req.body.warrantMan) {
                warrantMan = await db.getWarrantManByName(req.body.warrantMan)
            }
            const data = {
                id: req.params.id,
                is_ordertaking: req.body.ordertaking ? 1 : 0,
                cartype: req.body.cartype ? req.body.cartype : '',
                loan_amount: req.body.loanAmount ? req.body.loanAmount : 0,
                warrant: warrantMan ? warrantMan.id : 0,
                notpass_id: notpass ? notpass.id : 0,
                cancellation_id: cancellation ? cancellation.id : 0,
                trial_id: trial ? trial.id : 0,
                is_pick_car: req.body.pickcar ? 1 : 0,
                pass_time: req.body.passTime ? req.body.passTime : '',
                pick_car_time: req.body.pickCarTime ? req.body.pickCarTime : ''
            }
            const success = await db.updateWarrant(data) // 更新订单表数据

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    return router
})();